<?php

/**
 * Description of keywords_model
 *
 * @author terminus
 */
class Keywords_model extends CI_Model {

    private $tableName = 'keywords';

    public function __construct() {
        parent::__construct();
    }

    public function getKeywords($only_count = 0, $for_msgtype_id = 0, $limit = '', $offset = '') {
        if (1 != $only_count) {
            if ($for_msgtype_id > 0) {
                $this->db->where(array(
                    'for_msgtype_id' => $for_msgtype_id
                ));
            }

            if ($limit > 0) {
                $this->db->limit($limit);
                if ($offset > 0) {
                    $this->db->limit($limit, $offset);
                }
            }
        }

        $result = $this->db->get($this->tableName);
//        return $this->db->last_query();
        if ($result->num_rows() > 0) {
            if (1 == $only_count) {
                return $result->num_rows();
            }
            return $result->result();
        }
        return FALSE;
    }

    public function getKeyword($keyword, $is_by_id = 1, $for_msgtype_id = 0, $is_like = 0) {
        if (1 == $is_by_id) {
            $this->db->where(array('id' => $keyword));
        } else {
            if (1 == $is_like) {
                $this->db->like('keyword', $keyword);
            } else {
                $this->db->where(array('keyword' => $keyword));
            }
        }
        if ($for_msgtype_id > 0) {
            $this->db->where(array('for_msgtype_id' => $for_msgtype_id));
        }

        $result = $this->db->get($this->tableName);
//        return $this->db->last_query();
        if ($result->num_rows() > 0) {
            return $result->result();
        }
        return FALSE;
    }

    public function editKeyword($kid, $keyword, $dese, $for_msgtype_id) {
        $where['id'] = $kid;
        $set = array(
            'keyword' => $keyword,
            'description' => $dese,
            'for_msgtype_id' => $for_msgtype_id
        );

        if (TRUE === $this->db->update($this->tableName, $set, $where, 1)) {
            return TRUE;
        }
        return FALSE;
    }

    public function addKeyword($for_msgtype_id, $keyword, $desc) {
        $set = array(
            'keyword' => $keyword,
            'description' => $desc,
            'for_msgtype_id' => $for_msgtype_id
        );

        $this->db->insert($this->tableName, $set);
        $id = $this->db->insert_id();
        if ($id > 0) {
            return $id;
        }
        return FALSE;
    }

    public function delKeyword($keyword, $is_by_id = 1) {
        if (1 == $is_by_id) {
            $where['id'] = $keyword;
        } else {
            $where['keyword'] = $keyword;
        }

        $this->db->delete($this->tableName, $where, 1);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        }
        return FALSE;
    }

}
